package com.lightjet.macross.base.log.config;

import com.lightjet.macross.base.log.domain.LogContent;
import com.lightjet.macross.base.log.domain.LogIndex;
import com.lightjet.macross.base.log.service.LogContentService;
import com.lightjet.macross.base.log.service.LogIndexService;
import lombok.extern.java.Log;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.channels.Channel;
import java.util.Map;

@Log
@Component
@RabbitListener(queues = "ApiExecLogQueue")
public class ApiExecLogReciver {

    @Resource
    LogIndexService logIndexService;

    @Resource
    LogContentService logContentService;

    @RabbitHandler
    public void process(Map message){
        log.info("[ApiExecLogQueue]列队接收到新的消息");

        try {
            LogIndex logIndex = new LogIndex();
            logIndex.setCaption(SVFix(message.get("caption")));
            logIndex.setServicename(SVFix(message.get("servicename")));
            logIndex.setApiuri(SVFix(message.get("apiuri")));
            logIndex.setClientid(SVFix(message.get("clientid")));
            logIndex.setRequestip(SVFix(message.get("requestip")));
            logIndex.setMethod(SVFix(message.get("method")));
            logIndex.setUserkey(SVFix(message.get("userkey")));
            logIndex.setUserdes(SVFix(message.get("userdes")));
            logIndex.setCosttime(message.get("costtime") == null ? 0 : (Long) message.get("costtime"));
            logIndex.setResult(message.get("result") == null ? 0 : Byte.parseByte(message.get("result").toString()));
            logIndex.setInvokeclass(SVFix(message.get("invokeclass")));
            logIndex.setInvokemethod(SVFix(message.get("invokemethod")));
            logIndex.setLoglevel(LogIndex.LogLevelEnum.values()[message.get("loglevel") == null ? 0 : (Integer) message.get("loglevel")]);
            LogIndex saved = logIndexService.CreateAndFlush(logIndex);
            LogContent logContent = new LogContent();
            logContent.setLogIndex(saved);
            if(!"GET".equals(logIndex.getMethod().toUpperCase()))
            {
                logContent.setContent(SVFix(message.get("content")));
            }
            logContent.setParamtypes(SVFix(message.get("paramtypes")));
            logContent.setParamvalues(SVFix(message.get("paramvalues")));
            logContentService.CreateAndFlush(logContent);
        }
        catch (Exception e)
        {
            log.warning("消息处理失败：" + e.getMessage());
        }

    }

    private String SVFix(Object val){
        return val == null? "": val.toString();
    }
}
